package com.example.parsing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.dsl.IntegrationFlow;
import org.springframework.integration.dsl.IntegrationFlows;
import org.springframework.integration.dsl.MessageChannels;
import org.springframework.integration.file.dsl.Files;
import org.springframework.messaging.MessageChannel;

import java.io.File;


@Configuration
public class Parsing {
	
	private final JsonMessageHandler messageHandler;
	
	private final static Logger logger = LoggerFactory.getLogger(Parsing.class);
	
	private final TxtMessageHandler txtMessageHandler;
	
	public Parsing(JsonMessageHandler messageHandler, TxtMessageHandler txtMessageHandler) {
		this.messageHandler = messageHandler;
		this.txtMessageHandler = txtMessageHandler;
	}
	
	@Bean
	IntegrationFlow accessAndExcelFile(
				@Value("${input-directory:/home/ftpuser/js}") File in) {
		logger.info("access和excel文本准备进行设备注册或者上报");
		return IntegrationFlows.from(
					Files.inboundAdapter(in).preventDuplicates(false).regexFilter(".*\\.json$"),
					x -> x.poller(y -> y.fixedRate(2000)))
					.channel(fileChannel())
					.handle(messageHandler).get();
		
	}
	
	@Bean
	IntegrationFlow txtFile(
				@Value("${input-directory:/home/ftpuser/txt}") File in) {
		logger.info("txt文本进行数据上报和注册");
		return IntegrationFlows.from(
					Files.inboundAdapter(in).preventDuplicates(false).regexFilter(".*\\.json"),
					x -> x.poller(y -> y.fixedRate(10000)))
					.channel(txtChannel())
					.handle(txtMessageHandler)
					.get();
	}
	
	
	@Bean
	MessageChannel fileChannel() {
		return MessageChannels.publishSubscribe().get();
	}
	
	@Bean
	MessageChannel txtChannel() {
		return MessageChannels.publishSubscribe().get();
	}
}


